package com.ruoyi.web.cp.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.web.core.config.ConfigLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Service
public class SsqService {
    @Autowired
    private HttpService httpService;
    @Autowired
    private WinxinService winxinService;
    @Autowired
    private ConfigLoader configLoader;


    public String getSsqList(String ticketId, String name, String maxIssue, Map<String, Object> maxMap, String fileName) {
        String mm = String.valueOf(maxMap.get("mm"));
        String format = DateUtil.format(new Date(), "mm");
        if (mm != null && mm.equals(format)) {
            return maxIssue;
        } else {
            maxMap.put("mm", format);
        }
        JSONObject data = httpService.sendLeyuCpList(ticketId);
        JSONArray array;
        if ("0".equalsIgnoreCase(data.getString("code"))
                && CollUtil.isNotEmpty(array = data.getJSONArray("data"))) {
            data = array.getJSONObject(0);
            String issue1 = data.getString("issue");
            if (!Objects.equals(maxIssue, issue1)) {
                log.info("{}===>{}", name, issue1);
                maxIssue = issue1;
                List<String> msgs = new ArrayList<>();
                msgs.add(name);
                msgs.add(issue1);
                msgs.add(data.getString("code"));

                List<String> ssqFit = getSsqFit(fileName);
                String[] strs = ssqFit.get(ssqFit.size() - 1).split(",");
                if (maxIssue.equals(strs[0])) {
                    return maxIssue;
                }

                String text = "{},{},{}";
                String maxYilou = getYilou(array);

                log.info("极速SSQ,code:{},maxYilou==>{}", data.getString("code"), maxYilou);

                int issue2 = getIssue(strs[0]);
                int issue3 = getIssue(maxIssue);

                String msg = null;
                if (Integer.parseInt(maxYilou) >= 1 && Integer.parseInt(maxYilou) < 14) {
                    if (Math.abs(issue2 - issue3) == 1) {
                        //连续，则从上一次记录翻倍开始
                        msg = StrUtil.format(text, maxIssue, maxYilou.equals("1") ? 1 : Integer.parseInt(strs[1]) * 2,
                                new BigDecimal(strs[2]).subtract(new BigDecimal(strs[1])));
                    } else {
                        //非连续，则从1开始
                        msg = StrUtil.format(text, maxIssue, 1, strs[2]);
                    }
                } else if (Integer.parseInt(maxYilou) == 0 && Math.abs(issue2 - issue3) == 1
                        && !"0".equals(strs[1])) {
                    //yilou=0且连续，则从fit++
                    msg = StrUtil.format(text, maxIssue, 0, new BigDecimal(strs[1]).multiply(new BigDecimal("1.236")).add(new BigDecimal(strs[2])));
                }
                if (msg != null) {
                    format = StrUtil.format("{},msg==>{}", name, msg);
                    log.info(format);
                    winxinService.sendTextMessage("1000009", format);
                    setSsqFit(msg, fileName);
                }
            }
        }
        return maxIssue;
    }

    private String getYilou(JSONArray datas) {
        int num = 0;
        for (int i = 0; i < datas.size(); i++) {
            JSONObject item = datas.getJSONObject(i);
            Integer lianxu = lianxu(item.getString("code"));
            if (lianxu != 2) {
                num++;
            } else {
                return num + "";
            }
        }
        return num + "";
    }

    private List<String> getSsqFit(String fileName) {
        return FileUtil.readLines(configLoader.getGamenamesPath() + fileName, "utf8");
    }

    private void setSsqFit(String ssqFit, String fileName) {
        FileUtil.writeLines(Collections.singletonList(ssqFit), configLoader.getGamenamesPath() + fileName, "utf8", true);
    }

    private static int getIssue(String issue) {
        String str = issue.split(",")[0];
        int num = Integer.parseInt(str.substring(str.indexOf("-") + 1));
        return num == 1 ? 1441 : num;
    }

    public static void main(String[] args) {
        System.out.println(getIssue("20250507-0001"));
        System.out.println(getIssue("20250507-0002"));
    }

    private static Integer lianxu(String code) {
        String[] codes = code.split(",");
        Set<String> set = new HashSet<>();
        for (int i = 1; i < codes.length - 1; i++) {
            if (Integer.parseInt(codes[i]) - Integer.parseInt(codes[i - 1]) == 1) {
                set.add(codes[i]);
                set.add(codes[i - 1]);
            }
        }
        return set.size();
    }
}
